//
//  SettingMediaViewController.m
//  PhotoFrame
//
//  Created by William on 11-5-14.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import <AssetsLibrary/AssetsLibrary.h>
#import "SettingMediaViewController.h"
#import "GlobalSettingUtils.h"
#import "SettingThumbnailViewController.h"

@interface SettingMediaViewController (private)
- (void) reloadGroups;
@end

@implementation SettingMediaViewController
@synthesize delegate;

@synthesize library=library_;
@synthesize groups=groups_;
@synthesize assets=assets_;
@synthesize elements=elements_;
@synthesize orderElements=orderElements_;
@synthesize thumbnailCache=thumbnailCache_;

@synthesize filter=_filter;
@synthesize mediaType;
@synthesize headTitle;
/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
 // Custom initialization
 }
 return self;
 }
 */

/*
 // Implement loadView to create a view hierarchy programmatically, without using a nib.
 - (void)loadView {
 }
 */

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] 
								   initWithTitle:@"Done" 
								   style:UIBarButtonItemStyleBordered 
								   target:self action:@selector(closePop)];
	self.navigationItem.rightBarButtonItem = doneButton;
	[doneButton release];
	
    if (!self.elements) {
        elements_ = [[NSMutableDictionary alloc] init];
    }
    if (!self.orderElements) {
        orderElements_ =[[NSMutableArray alloc] init];
    }
    if (!self.thumbnailCache) {
        thumbnailCache_ = [[NSMutableArray alloc] init];
    }
    groups_ = [[NSMutableArray alloc] init];
    [self reloadGroups];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    return YES;
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}


- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.library = nil;
	self.groups = nil;
	self.assets = nil;
    self.elements = nil;
    self.thumbnailCache = nil;
    
    self.filter = nil;
    self.mediaType = nil;
    self.headTitle = nil;
}


- (void)dealloc {
    [_filter release];
    
    [super dealloc];
}

#pragma mark -
#pragma mark Table View Data Source Methods
- (NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	static NSString *identify = @"SimpleTableIdentifier";
	
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] 
				 initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identify] autorelease];
	}
    cell.textLabel.text = @"全てを選択";
    cell.textLabel.textAlignment = UITextAlignmentCenter;
	return cell;
}

#pragma mark -
#pragma mark Table View Delegate Methods
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self allSelected];
    
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return self.headTitle;
}

- (void) closePop {
	[delegate closePopover];
}

- (void) setThumbnailView {
    float startX = 10.0;
    float x = startX;
    float y = 100.0;
    float w = 75.0;
    float h = 75.0;
    float hspan = 85.0;
    float vspan = 80.0;
    
    for (int i = 0; i < self.orderElements.count; i++) {
        int picNum = i + 1;
        if (picNum % 5 == 0) {
            x = startX;
        }
        NSString *urlStr = ([self.orderElements objectAtIndex:i]);
        ALAsset *asset = [self.elements objectForKey:urlStr];
        
        NSMutableDictionary *dict = [GlobalSettingUtils getPlayList];
        
        // perpare the controller
        SettingThumbnailViewController *thumbnail = [[SettingThumbnailViewController alloc] initWithNibName:@"SettingThumbnailView" bundle:nil];
        
        CGRect rect = CGRectMake(x, y, w, h);
        UIImage *image = [UIImage imageWithCGImage:[asset thumbnail]];
        
        [((UIButton*) thumbnail.view) setImage:image forState:UIControlStateNormal];
        [thumbnail.view setFrame:rect];
        thumbnail.url = urlStr;
        thumbnail.type = self.mediaType;
        thumbnail.seq = i;
        if ([dict objectForKey:urlStr] == nil) {
            thumbnail.isMark = NO;
            [thumbnail.markImageView setHidden:YES];
        } else {
            thumbnail.isMark = YES;
            [thumbnail.markImageView setHidden:NO];
        }
        [thumbnail.markImageView setUserInteractionEnabled:NO];
        
        [self.thumbnailCache addObject:thumbnail];
        [thumbnail release];
        
        if (picNum % 4 == 0) {
            y += vspan;
        }
        x += hspan;
    }
}

#pragma mark -
#pragma mark Assets management
- (void)reloadGroups {
    if (!self.library) {
		library_ = [[ALAssetsLibrary alloc] init];
	}
    
    void (^assetEnumerator)(ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop) {
        if(result != NULL) {
            NSDictionary *url = [result valueForProperty:ALAssetPropertyURLs];
            NSArray *array = [url allValues];
            NSLog(@"url: %@", url);
            
            NSString *urlStr = [NSString stringWithFormat:@"%@", [array objectAtIndex:0]];
            [self.elements setObject:result forKey:urlStr];
            [self.orderElements addObject:urlStr];
        }
    };
    
    self.assets = [[NSMutableArray alloc] init];
    
	ALAssetsLibraryGroupsEnumerationResultsBlock resultBlock =
	^(ALAssetsGroup *assetsGroup, BOOL *stop) {
		if (assetsGroup) {
            [assetsGroup setAssetsFilter:self.filter];
            [assetsGroup enumerateAssetsUsingBlock: assetEnumerator];
            [self.groups addObject:assetsGroup];
            NSLog(@"grouop: %@", self.groups);
		} else {
            [self setThumbnailView];
        }
	};
    
	[self.library enumerateGroupsWithTypes:ALAssetsGroupAll
                                usingBlock:resultBlock
                              failureBlock: ^(NSError *error) {
                                  NSLog(@"No groups");
                              }];
    
    [self performSelector:@selector(loadThumbnail) withObject:nil afterDelay:1];
}

- (void) allSelected {
    for (int i = 0; i < self.thumbnailCache.count; i++) {
        SettingThumbnailViewController *thumbnail = [self.thumbnailCache objectAtIndex:i];
        thumbnail.isMark = YES;
        [thumbnail.markImageView setHidden:NO];
        
        [GlobalSettingUtils setPlayListForValue:self.mediaType forKey:thumbnail.url];
    }
}

- (void) loadThumbnail {
    for (int i = 0; i < self.thumbnailCache.count; i++) {
        SettingThumbnailViewController *thumbnail = [self.thumbnailCache objectAtIndex:i];
        [self.tableView addSubview:thumbnail.view];
    }
}

@end
